﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Industry.Contracts.Model.Enum;

namespace ZhonTai.Industry.Contracts.Interactive
{
    /// <summary>
    /// 监控基类
    /// </summary>
    public abstract class BaseMonitor
    {
        /// <summary>
        /// 线程状态 true执行中 false阻塞中
        /// </summary>
        private bool _ThreadStatus = false;
        private int _InitialInterval;
        public bool ThreadStatus
        {
            get { return _ThreadStatus; }
            set
            {
                _ThreadStatus = value;
            }
        }
        /// <summary>
        /// 控制启动停止
        /// </summary>
        [NonSerialized]
        private AutoResetEvent _m_AutoResetEvent = new AutoResetEvent(false);
        [JsonIgnore]
        private AutoResetEvent m_AutoResetEvent
        {
            get
            {
                if (_m_AutoResetEvent == null)
                {
                    _m_AutoResetEvent = new AutoResetEvent(false);
                }
                return _m_AutoResetEvent;
            }
            set { _m_AutoResetEvent = value; }
        }

        /// <summary>
        /// 线程控制
        /// </summary>
        [NonSerialized]
        private Thread m_Thread;

        protected BaseMonitor(int initialInterval = 300)
        {
            _InitialInterval = initialInterval;
            m_Thread = new Thread(Process);
            m_Thread.IsBackground = true;
            m_Thread.Start();
        }
        private void Process()
        {
            while (true)
            {
                if (!ThreadStatus)
                {
                    m_AutoResetEvent.WaitOne();
                }
                else
                {
                    Execute();
                }
                Thread.Sleep(_InitialInterval);
            }
        }

        protected abstract void Execute();

        public void Start()
        {
            if (!ThreadStatus)
            {
                ThreadStatus = true;
                m_AutoResetEvent.Set();
            }
        }

        public virtual void Stop()
        {
            if (ThreadStatus)
            {
                ThreadStatus = false;
            }
        }
    }
}